﻿using System.Text;
using PhiStore.Util;

namespace PhiStore
{
    /// <summary>
    /// A collection of methods for generating and validating keys
    /// </summary>
    public static class KeyHelper
    {
        /// <summary>
        /// A string of valid characters for the PhiStore
        /// </summary>
        public const string ValidCharacters = "abcdefghijklmnopqrstuvwxyz1234567890+-_";

        /// <summary>
        /// generates a random key with purely valid characters
        /// </summary>
        /// <param name="length">the length (in characters) of the key</param>
        /// <returns>The generated key</returns>
        public static string GenerateObjectKey(int length)
        {
            char[] validchars = ValidCharacters.ToCharArray();

            StringBuilder sb = new StringBuilder(length);

            for (int i = 0; i < length; i++)
            {
                char letter = validchars[RandomGenerator.Integer(validchars.Length)];
                sb.Append(letter);
            }
            return sb.ToString();
        }

        /// <summary>
        /// Shorthand for GenerateObjectKey(64)
        /// </summary>
        /// <returns>The 64 characters long generated key</returns>
        public static string GenerateObjectKey()
        {
            return GenerateObjectKey(64);
        }

        /// <summary>
        /// Verifies that the key is valid
        /// </summary>
        /// <param name="key">The key to check</param>
        /// <returns>Whether or not the ley is valid</returns>
        public static bool KeyIsValid(string key)
        {
            char[] validchars = ValidCharacters.ToCharArray();
            
            if (key.Contains(" ") || key.Equals(string.Empty))
            {
                return false;
            }

            foreach(char c in validchars)
            {
                key = key.Replace(c, ' ');
            }
            return key.Trim().Equals(string.Empty); //all chars are valid
        }
    }
}
